/* Controllers */

var appControllers = angular.module('appControllers', []);

// 微信服务请求
appControllers.controller('FwqqCtrl-wx', function($rootScope, $scope, $http,$ionicActionSheet, $ionicPopup,$ionicLoading,$state, Camera) {
	
	App.setScope($scope);
	App.userquery();

	var user = Session.loadObject("user");
	if(user) {
		$scope.userinfo = user;
	}

	$scope.formData={};
	//$scope.formData.category='SERVICEREQ_CATEGORY_10';
	$scope.showimgdiv = false;

	$scope.selecttype = function(typename){
		$scope.formData.title=typename+"-APP";
	}

	$scope.eventDispatch = function() {

		if ($scope.formData.category == undefined || $scope.formData.category == '') {
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请选择服务请求类型！'
			});
			return;
		}
		if ($scope.formData.description == undefined || $scope.formData.description == '') {
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请输入描述！'
			});
			return;
		}

		var paramdata = {
			title : $scope.formData.title,
			//category:$scope.formData.category,
			description : $scope.formData.description,
			files:$scope.fileids
		};
		if ($scope.formData.majorevent == true) {
			paramdata.majorevent = "Y";
		} else {
			paramdata.majorevent = "N";
		}
		var reqdata = {
			'method' : 'ServiceReqDispatch',
			'param' : JSON.stringify(paramdata),
			'dataFrom' : 'weixin'
		};

		 //alert(JSON.stringify(paramdata))
		 //return;

		App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
			
			App.myNotice("新增服务请求成功");
			window.history.back();
		});
	}


	  /*Photo*/
	$scope.images_url = "";
  function onPhotoDone(imageURI){uploadPhoto(imageURI);}
  function onPhotoFail(message){Yibeiban.myLogger('Photo Failed: ' + message);}
  function makePhoto(){

  	var use_camera = Store.loadObject("use_camera");
  	if(use_camera != undefined && use_camera == "1"){
  		navigator.camera.getPicture(onPhotoDone, onPhotoFail, { quality: 100, targetWidth: 500, targetHeight: 500, destinationType: navigator.camera.DestinationType.FILE_URI});

  	}else{

	  	var confirmPopup = $ionicPopup.confirm({
			title : '<strong>提示</strong>',
			template : 'IT自助服务将会使用手机的摄像头，请授权。',
			okText : '允许',
			cancelText : '不允许'
		});

		confirmPopup.then(function(res) {
			if (res) {
				Store.saveObject("use_camera","1");
				navigator.camera.getPicture(onPhotoDone, onPhotoFail, { quality: 100, targetWidth: 500, targetHeight: 500, destinationType: navigator.camera.DestinationType.FILE_URI});
			}
		});
  	}

  }
  function takePhoto(){
    navigator.camera.getPicture(onPhotoDone, onPhotoFail, { quality: 100, targetWidth: 500, targetHeight: 500, destinationType: navigator.camera.DestinationType.FILE_URI
    ,sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM });
  }
  function uploadPhoto(imageURI){
  	//alert("imageURI==="+imageURI);
  	$ionicLoading.show({content : '正在上传...',animation : 'fade-in'});
    var done = function(r){
    	//alert("upload done"+r.response);
    	$ionicLoading.hide();

      try{
      	var json = JSON.parse(r.response);
      	if(json.code=="200"){
      		var ids = json.object.ids;
      		$scope.fileids=ids;
      		$scope.images_url = imageURI;
      		$scope.showimgdiv = true;
      		App.myNotice("图片上传成功",2000);
      	}else{
      		App.myNotice("图片上传失败",2000);
      	}
      }catch(e){
      	App.myNotice("图片上传失败"+e,2000);
      }

      
      //alert($scope.images_list.length);
    };

    var fail = function(e){
    	$ionicLoading.hide();
    	App.myNotice("图片上传失败fail"+e,2000);
    };

    var options = new FileUploadOptions();
    options.params  = {'method' : 'FileUpload'};
    options.fileKey ="file";
    options.fileName="test.jpg";
    options.mimeType="image/jpeg";

    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI(OpenAPI.requrl), done, fail, options);
  }

$scope.delimg=function(){
	$scope.images_url = "";
	$scope.fileids="";
   $scope.showimgdiv = false;
}


  $scope.showActionsheet = function(){
    $ionicActionSheet.show({
      titleText : '上传图片',
      cancelText: '取消',
      buttons   : [{text:'拍照'},{text:'从相册中选取'}],
      cancel    : function(){},
      buttonClicked : function(index){
        switch(index){
          case  1:takePhoto();break;
          case  0:
          default:makePhoto();break;
        }
        return true;
      }
    });
  };

});

// 服务请求列表
appControllers.controller('FwqqListCtrl', function($scope, $http, $state, $stateParams) {
	
	var p = {
		"type" : "ServiceReq",
		"dbtype":'0'
	};
	var reqdata = {
		'method' : 'OrderList',
		'param' : JSON.stringify(p),
		'fromType': 'weixin'
	};

	if($stateParams.comment === "true") {
		reqdata.comment = true;
	}

	$scope.scrollItems = [];
	$scope.hasdata = true;

	var expiredTime = 48*60*60*1000;
	//var processNames = ['准备服务请求','验证和记录','分派工单','实施交付/投诉处理','用户确认','关闭工单','绩效评分','归档','处理完成'];

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
		for (var i = 0; i < data.object.length; i++) {
				var obj = data.object[i];
				/*if (obj.statu == "0") {
					obj.statuname = "未签收";
				} else if (obj.statu == "1") {
					obj.statuname = "已签收";
				} else if (obj.statu == "2") {
					obj.statuname = "已结束";
				} else {
					obj.statuname = "---";
				}*/
				if(obj && obj.endDate && obj.endDate > 0) {
					if(obj.hasOpinion || ((new Date()).getTime()-obj.endDate) > expiredTime) {
						obj.commentTitle = "查看评价";
					}else {
						obj.commentTitle = "我要评价";
					}
				}

				if(obj && obj.statuname) {
					obj.processName = obj.statuname;
					// var idx = processNames.indexOf(obj.statuname);
					// if(idx < 5 && idx >= 0) {
					// 	obj.processName = '正在处理';
					// }else if(idx >= 5) {
					// 	obj.processName = '处理完成';
					// }else {
					// 	console.log('无法识别的流程节点名称:' + obj.statuname);
					// }
				}

				$scope.scrollItems.push(obj);
			}
		if(data.object.length==0){
			$scope.hasdata = false;
		}
	});

	$scope.detail = function(obj) {

		$state.go('fuwuqingqiudetail', {
			'id' : obj.serialno
		});
	}

	$scope.comment = function(obj) {
		$state.go('add-comment', {
			'id' : obj.serialno
		});
	} 
});

// 服务请求详情查询
appControllers.controller('Fwqqdetail', function($scope, $http, $stateParams) {

	App.setScope($scope);
	App.userquery();
	var p = {
		"serialno" : $stateParams.id
	};
	
	var reqdata = {
		'method' : 'OrderQuery',
		'param' : JSON.stringify(p)
	};

	App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){

		var obj = data.object;
		var user = Session.loadObject("user");
		obj.typeName=App.getTypeName(obj.category);
		
		$scope.data = obj;
		$scope.data.serialno = $stateParams.id;

		if(user) {
			$scope.userinfo = user;
		}
    });

});

appControllers.controller('LoginFormCtrl', function($rootScope, $scope, $http,
		$location, $ionicPopup, $state) {


	// test
	var userObject = {
		"code": 200,
		"message": "",
		"object": {
			"replyPermission": false,
			"name": "测试账户",
			"mobile": "18696531031",
			"usertype": "1",
			"sessionId": "DB628E395DA843707CE750AEA5C51E28",
			"department": "服务台",
			"userid": "000000005eac8c0b015eaca7b2020007",
			"shizhuren": false,
			"email": "18696531031@qq.com",
			"username": "18696531031"
		}
	};
	Session.saveObject("user", userObject.object);
	Session.saveObject("usertype", userObject.object.usertype);
	Store.saveObject("cacheusername",userObject.object.username);

	$rootScope.isdisabled=false;

	$scope.login = function(action) {
		if(action == 'service') {
			$state.go('fuwuqingqiu-wx');
		}else if(action == 'history') {
			$state.go('fuwuqingqiulist');
		}else if(action == 'comment') {
			$state.go('fuwuqingqiulist',{ comment: true });
		}
//		var alertPopup = $ionicPopup.alert({
//			title : '测试',
//			template : window.location.href
//		});

//		var username = '51859';
//		var pwd = '654321';

//		var reqdata = {
//			'method' : 'login',
//			'param' : JSON.stringify({username:username, pwd: pwd})
//		};

//		App.ajaxPost(OpenAPI.requrl, $.param(reqdata), function(data){
//
//			var usertype = data.object.usertype;
//
//	 		Session.saveObject("user", data.object);
//			Session.saveObject("usertype", usertype);
//
//			Store.saveObject("cacheusername",username);
//
//			$rootScope.usertype = Session.loadObject("usertype");
//
//			alertPopup.then(function(){
//				if(action == 'service') {
//					$state.go('fuwuqingqiu-wx');
//				}else if(action == 'history') {
//					$state.go('fuwuqingqiulist');
//				}else if(action == 'comment') {
//					$state.go('fuwuqingqiulist',{ comment: true });
//				}
//			});
//    	});
	};

	$scope.genValidateCode = function() {
		var seed = new Array('abcdefghijklmnopqrstuvwxyz',
				'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789'); // 创建需要的数据数组
		var idx, i;
		var result = ''; // 返回的结果变量
		for (i = 0; i < 4; i++) // 根据指定的长度
		{
			idx = Math.floor(Math.random() * 3); // 获得随机数据的整数部分-获取一个随机整数
			result += seed[idx].substr(Math.floor(Math.random()
					* (seed[idx].length)), 1);// 根据随机数获取数据中一个值
		}

		$scope.validatecode = result;

		Session.saveObject("validcode", result);

		return result; // 返回随机结果
	};

	$scope.validatecode = $scope.genValidateCode();
});

angular.module('ItsmApp').controller('addCommentCtrl', function($scope, $http,$state, $stateParams) {

	var user = Session.loadObject("user");

	$scope.formData={
		grade: 4,
		serviceGrade: 4,
		isReadonly:  false
	};

	if($stateParams.id) {
		App.ajaxPost(OpenAPI.getCommentUrl + $stateParams.id, {}, function(data){
			$scope.formData.grade = data.data.grade;
			$scope.formData.serviceGrade = data.data.serviceGrade;
			$scope.formData.content = data.data.content;
			$scope.formData.isReadonly = true;
	    });
	}
	
	$scope.dosubmit=function(){

		if($scope.formData.content==undefined || $scope.formData.content==""){
			var alertPopup = $ionicPopup.alert({
				title : '输入错误',
				template : '请输入内容描述'
			});
			return;
		}

		var p = {
			"userid" : user.userid,
			"username" : user.name
		};
		var reqdata = {
			'method' : 'NoteAdd',
			'param' : JSON.stringify(p),
			"content" : $scope.formData.content,
			"workOrderId": $stateParams.id,
			"grade": $scope.formData.grade,
			"serviceGrade": $scope.formData.serviceGrade
		};

		App.ajaxPost(OpenAPI.saveCommentUrl, $.param(reqdata), function(data){
			App.myNotice("提交成功");
			history.back();
		});
	}
});
